package exp8;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class WrongDateException extends Exception {
	public WrongDateException(String message) {
		super(message + "不是合法的日期字符串");
	}
}

class BaseFrame extends JFrame {
	public BaseFrame(String title) {
		setLayout(null);
		setTitle(title);
		setSize(500, 250);
		setLocationRelativeTo(null);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void showMe() {
		setVisible(true);
	}
}

class DateDemo {
	JLabel l1 = new JLabel("输入日期字符串：");
	JLabel l2 = new JLabel("显示区");
	JTextField jtf = new JTextField();
	JButton bt = new JButton("转换");

	public static Date convert(String t) throws WrongDateException {
		Date d = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d = format.parse(t);
		} catch (ParseException e) {
			throw new WrongDateException(t);
		}
		return d;

	}

	void init() {
		BaseFrame f = new BaseFrame("DateDemo");
		l1.setSize(150, 50);
		l1.setLocation(0, 0);
		f.add(l1);
		l2.setSize(200, 50);
		l2.setLocation(0, 150);
		f.add(l2);
		jtf.setSize(400, 30);
		jtf.setLocation(10, 60);
		f.add(jtf);
		bt.setSize(60, 40);
		bt.setLocation(420, 55);
		f.add(bt);
		f.showMe();
		MyActionListener listener = new MyActionListener();

		bt.setActionCommand("convert");
		bt.addActionListener(listener);
	}

	class MyActionListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			String t = jtf.getText();
			Date datas;
			if (e.getActionCommand() == "convert") {
				try {
					datas = convert(t);
					SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
					l2.setText(format.format(datas));
				} catch (WrongDateException e1) {
					l2.setText(e1.getMessage());
				}
			}

		}

	}
}

public class Exp8_3 {
	public static void main(String[] args) {
		new DateDemo().init();

	}
}
